<template>
    <!-- 中间主操作区和右侧特效类型选择侧栏并排 -->
    <div v-show="visible" class="relative">
        <!-- 主操作区 -->
        <div
            class="w-[440px] min-w-[440px] max-w-[440px] flex flex-col h-full px-0 pt-4 pb-0 bg-[#232428] relative select-none z-10">
            <!-- 顶部大标题 -->
            <div class="flex-1 overflow-auto">
                <div class="mx-6 mb-6">
                    <div class="text-xl font-bold text-white leading-none">Creative Effects</div>
                </div>
                <div class="mx-6">
                    <div class="text-sm text-white font-medium mb-2">Select Effect</div>
                </div>
                <div class="mx-6 mb-6">
                    <div
                        class="flex items-center justify-center rounded-md border border-neutral-700 px-2 py-2 relative">
                        <img :src="effects[selectedEffectIndex].img"
                            class="w-12 h-12 rounded-md object-cover mr-3" />
                        <div class="flex-1 flex flex-col items-start justify-center">
                            <div class="flex items-center">
                                <span class="text-white text-base font-bold leading-none">{{
                                    effects[selectedEffectIndex].title }}</span>
                                <span v-if="effects[selectedEffectIndex].hot"
                                    class="ml-3 text-[12px] bg-[#ff5f6d] text-white rounded px-2 py-1 font-bold leading-none">Hot</span>
                            </div>
                        </div>
                        <button @click="showEffectPanel = !showEffectPanel"
                            class="absolute right-0 top-1/2 -translate-y-1/2 w-11 h-11 rounded-[12px] bg-[#232428] flex items-center justify-center text-[22px] text-white hover:bg-[#232428]/80 transition-all shadow-[0_2px_8px_0_rgba(0,0,0,0.10)]">
                            <icon-park-switch theme="outline" size="16" fill="#fff" />
                        </button>
                    </div>
                </div>
                <div class="mx-6" v-if="effects[selectedEffectIndex].step">
                    <div class="text-sm text-white font-medium mb-2">Step 1: Please upload a single-person photo</div>
                </div>
                <div class="mx-6 mb-6" v-if="effects[selectedEffectIndex].step">
                    <div class="rounded-md bg-[#18191c] px-2 py-2 flex items-center">
                        <img :src="effects[selectedEffectIndex].example || effects[selectedEffectIndex].img"
                            class="w-22 h-18 object-contain rounded-md mr-6" />
                        <div class="flex-1 flex flex-col justify-center">
                            <div class="text-white text-sm font-bold mb-2 leading-none">Upload a portrait photo</div>
                            <div class="text-[#bfc0c2] text-xs leading-tight">A front-facing, unobstructed, and clear photo will yield the best results.</div>
                        </div>
                    </div>
                </div>
                <!-- 数量选择tab，内容自适应高端像素级还原 -->
                <div class="mx-6 mb-6 flex items-center gap-2"
                    v-if="effects[selectedEffectIndex].limit && effects[selectedEffectIndex].limit > 1">
                    <div class="flex justify-center items-center w-full transition-all p-1 gap-2 duration-200 border border-[#bfc0c2]/40 text-sm text-[#bfc0c2] rounded-md select-none">
                        <div
                            class="flex-1 flex justify-center items-center py-1 rounded-md cursor-pointer transition-all duration-200"
                            :class="uploadTabIndex === 2 ? 'bg-[#ffffff29] text-[#7fff00] font-bold shadow' : 'hover:bg-[#ffffff29]'"
                            @click="uploadTabIndex = 2"
                        >
                            2 single-person photos
                        </div>
                        <div
                            class="flex-1 flex justify-center items-center py-1 rounded-md cursor-pointer transition-all duration-200"
                            :class="uploadTabIndex === 1 ? 'bg-[#ffffff29] text-[#7fff00] font-bold shadow' : 'hover:bg-[#ffffff29]'"
                            @click="uploadTabIndex = 1"
                        >
                            1 two-person photo
                        </div>
                    </div>
                </div>
                <div class="mx-6 mb-7">
                    <!-- 两张单人照片上传 -->
                    <template v-if="uploadTabIndex === 2">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <div class="text-sm text-white font-medium mb-2">First Photo</div>
                                <Upload 
                                    placeholder="Supports jpg/png format"
                                    :value="fileList.slice(0, 1)"
                                    @upload="(files) => handleUploadChange([...files, ...fileList.slice(1)])"
                                    accept="image/*"
                                    :height="'200px'"
                                    :width="'100%'"
                                    :style="'text-xs mt-2'"
                                    :icon-component="imageIcon"
                                    :icon-size="24"
                                    icon-color="text-white/50"
                                    :menu-items="[{ label: 'Local file', icon: 'icon-park-upload', action: 'local' }]"
                                    :popup="'80px'"
                                    :url="''"
                                    :is-upload="true"
                                    :max-count="1"
                                />
                            </div>
                            <div>
                                <div class="text-sm text-white font-medium mb-2">Second Photo</div>
                                <Upload 
                                    placeholder="Supports jpg/png format"
                                    :value="fileList.slice(1, 2)"
                                    @upload="(files) => handleUploadChange([...fileList.slice(0, 1), ...files])"
                                    accept="image/*"
                                    :height="'200px'"
                                    :width="'100%'"
                                    :style="'text-xs mt-2'"
                                    :icon-component="imageIcon"
                                    :icon-size="24"
                                    icon-color="text-white/50"
                                    :menu-items="[{ label: 'Local file', icon: 'icon-park-upload', action: 'local' }]"
                                    :popup="'80px'"
                                    :url="''"
                                    :is-upload="true"
                                    :max-count="1"
                                />
                            </div>
                        </div>
                    </template>
                    <!-- 一张双人照片上传 -->
                    <template v-else>
                        <Upload 
                            placeholder="Supports jpg/png format"
                            :value="fileList"
                            @upload="handleUploadChange"
                            accept="image/*"
                            :height="'200px'"
                            :width="'100%'"
                            :style="'text-xs mt-2'"
                            :icon-component="imageIcon"
                            :icon-size="24"
                            icon-color="text-white/50"
                            :menu-items="[{ label: 'Local file', icon: 'icon-park-upload', action: 'local' }]"
                            :popup="'80px'"
                            :url="''"
                            :is-upload="true"
                            :max-count="1"
                        />
                    </template>
                </div>
                <div class="mx-6 mb-7" v-if="selectedEffectIndex == 0 || selectedEffectIndex == 2">
                    <div class="flex items-center justify-between rounded-md bg-white/5 px-4 py-2">
                        <div
                            class="text-sm text-white font-medium flex items-center gap-1 leading-none">
                            {{ selectedEffectIndex == 0 ? 'Group Celebration Video Effect' : 'Flashlight Effect' }}
                            <span class="text-[12px] text-[#bfc0c2] font-normal cursor-pointer">
                                <a-popover>
                                    <icon-park-info theme="outline" size="14" fill="#bfc0c2" />
                                    <template #content>
                                        <video :src="effects[selectedEffectIndex].effect"
                                            class="w-44 h-44 object-cover" autoplay muted loop></video>
                                    </template>
                                </a-popover>
                            </span>
                        </div>
                        <label class="inline-flex relative items-center cursor-pointer select-none">
                            <input type="checkbox" v-model="multiMode" class="sr-only peer">
                            <div
                                class="w-9 h-5 bg-[#232428] border-0 peer-focus:outline-none rounded-full relative transition-all duration-200 peer-checked:bg-[#7fff00] shadow-sm after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all after:duration-200 peer-checked:after:translate-x-4">
                            </div>
                            <span class="ml-2 text-sm text-white font-normal">{{ multiMode ? 'On' : 'Off'
                                }}</span>
                        </label>
                    </div>
                </div>
            </div>
            <!-- 下拉和按钮吸底区域 -->
            <div class="absolute left-0 bottom-0 w-full px-6 pb-6 bg-[#232428] z-20">
                <div class="flex flex-col gap-4">
                    <!-- 自定义下拉菜单 -->
                    <div class="relative">
                        <div @click="showModeDropdown = !showModeDropdown"
                            class="flex items-center justify-between w-full h-10 px-4 rounded-md border border-[#bfc0c2]/40 bg-[#232428] cursor-pointer text-sm text-[#bfc0c2] focus:ring-0 focus:outline-none transition-all">
                            <span class="text-[#7fff00]">{{ modeOptions.find(opt => opt.value ===
                                selectedMode)?.label }}</span>
                            <svg :class="['w-4 h-4 ml-2 text-[#bfc0c2] transition-transform duration-200', showModeDropdown ? 'rotate-180' : '']"
                                fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round"
                                    d="M19 9l-7 7-7-7" />
                            </svg>
                        </div>
                        <transition enter-active-class="transition-all duration-200 ease-in-out"
                            leave-active-class="transition-all duration-200 ease-in-out"
                            enter-from-class="translate-y-4 opacity-0"
                            enter-to-class="translate-y-0 opacity-100"
                            leave-from-class="translate-y-0 opacity-100"
                            leave-to-class="translate-y-4 opacity-0">
                            <div v-if="showModeDropdown"
                                class="absolute left-0 bottom-full mb-2 w-full rounded-md bg-[#18191c] border border-[#18191c] z-30 overflow-hidden">
                                <div v-for="opt in modeOptions" :key="opt.value"
                                    @click="selectMode(opt.value)"
                                    class="px-6 py-4 cursor-pointer text-sm font-bold transition-all duration-200"
                                    :class="[
                                        selectedMode === opt.value
                                            ? 'bg-[#18191c] text-[#7fff00]'
                                            : 'bg-[#18191c] text-white hover:bg-[#232428] hover:text-[#7fff00]',
                                        opt.value === 1 ? 'rounded-t-md' : 'rounded-b-md',
                                        'flex items-center gap-2'
                                    ]">
                                    {{ opt.label }}
                                    <span v-if="opt.value === 2"
                                        class="ml-2 text-xs bg-[#1e2d1b] text-[#7fff00] px-2 py-0.5 rounded-md font-bold">VIP</span>
                                </div>
                            </div>
                        </transition>
                    </div>
                    <button
                        @click="handleGenerate"
                        :disabled="!canGenerate"
                        class="w-full bg-[#7fff00] hover:bg-[#5fd700] text-[#232428] font-bold h-12 rounded-md text-lg mt-2 transition-all disabled:opacity-50 disabled:cursor-not-allowed">
                        Generate Now
                    </button>
                </div>
            </div>
        </div>
        <!-- 右侧特效类型选择侧栏，绝对定位在主操作区右侧，层级在主操作区下方 -->
        <transition enter-active-class="transition-all duration-300 ease-in-out"
            leave-active-class="transition-all duration-300 ease-in-out"
            enter-from-class="-translate-x-[440px] opacity-0" enter-to-class="translate-x-0 opacity-100"
            leave-from-class="translate-x-0 opacity-100"
            leave-to-class="-translate-x-[440px] opacity-0">
            <div v-if="showEffectPanel"
                class="absolute top-0 z-1 left-[440px] h-full min-w-[440px] max-w-[440px] bg-[#18191c] flex flex-col p-6 border-r border-[#232428] overflow-hidden">
                <button @click="showEffectPanel = false"
                    class="absolute top-4 right-4 text-gray-400 hover:text-white text-2xl">
                    <icon-park-close theme="outline" size="16" fill="#fff" />
                </button>
                <div class="text-base font-bold mb-4 text-white leading-none">Creative Effects</div>
                <a-scrollbar class="overflow-auto">
                    <div class="grid grid-cols-2 gap-4 h-auto">
                        <div v-for="(item, i) in effects" :key="i" class="relative group cursor-pointer"
                            @click="selectedEffectIndex = i;">
                            <a-popover>
                                <div class="relative">
                                    <img :src="item.img"
                                        class="object-cover rounded-lg border border-transparent group-hover:border-[#ff5f6d] transition-all w-full h-full" />
                                    <div class="absolute left-0 bottom-0 w-full" style="height: 25%; background: linear-gradient(0deg, rgba(15,15,15,0.85) 80%, rgba(15,15,15,0) 100%); pointer-events: none;"></div>
                                    <div
                                        class="absolute left-2 bottom-2 text-white flex items-center gap-1 font-bold text-base drop-shadow z-10">
                                        <div class="mr-2">{{ item.title }}</div>
                                        <div class="bg-rose-600 text-white text-[10px] px-2 py-0.5 rounded-md"
                                            v-if="item.hot">Hot
                                        </div>
                                    </div>
                                </div>
                                <template #content>
                                    <video :src="item.video" class="w-44 h-44 object-cover" autoplay
                                        muted loop></video>
                                </template>
                            </a-popover>
                        </div>
                    </div>
                </a-scrollbar>
            </div>
        </transition>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import Upload from '@/components/upload/index.vue';
import { Effects, PictureOne, VideoTwo, ClothesCrewNeck, Switch, Close, AddPicture, Info } from '@icon-park/vue-next';
import { getOneImageEffectsVideo, getMultiImageEffectsVideo, getEffectsVideoResult } from '@/api';
import { Message } from '@arco-design/web-vue';

// 文件类型
interface FileType {
    url: string;
    file?: File;
}

// 视频生成状态
interface VideoTaskResult {
    task_status: number;
    task_result: string;
    task_msg: string;
}

export default defineComponent({
    name: 'Effect',
    components: {
        'icon-park-effects': Effects,
        'icon-park-picture': PictureOne,
        'icon-park-video': VideoTwo,
        'icon-park-clothes-crew-neck': ClothesCrewNeck,
        'icon-park-switch': Switch,
        'icon-park-close': Close,
        'icon-park-add-picture': AddPicture,
        'icon-park-info': Info,
        Upload
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    emits: ['video-generated'],
    data() {
        return {
            showEffectPanel: true,
            effects: [
                { title: 'Hug', img: '/images/4.png', example: '/images/4-1.png', video: '/videos/4.mp4', effect: '/videos/4-1.mp4', step: true, limit: 2, hot: true, effect_type: 1 },
                { title: 'Kiss', img: '/images/5.png', example: '/images/4-1.png', video: '/videos/5.mp4', step: true, limit: 2, hot: true, effect_type: 2 },
                { title: 'Heart Gesture', img: '/images/7.png', example: '/images/4-1.png', video: '/videos/7.mp4', step: true, limit: 2, hot: true, effect_type: 3 },
                { title: 'Colorful World', img: '/images/9.png', example: '/images/9-1.png', video: '/videos/9.mp4', step: true, limit: 1, effect_type: 1 },
                { title: 'Magic Spin', img: '/images/10.png', video: '/videos/10.mp4', step: false, limit: 1, effect_type: 2 },
                { title: 'Annoy Me', img: '/images/11.png', video: '/videos/11.mp4', step: false, limit: 1, effect_type: 3 },
                { title: 'Pinch Fun', img: '/images/12.png', video: '/videos/12.mp4', step: false, limit: 1, effect_type: 4 },
                { title: 'Everything Expands', img: '/images/13.png', video: '/videos/13.mp4', step: false, limit: 1, effect_type: 5 },
            ],
            selectedEffectIndex: 0,
            showModeDropdown: false,
            modeOptions: [
                { label: 'Standard Mode', value: 1 },
                { label: 'High Quality Mode', value: 2 }
            ],
            selectedMode: 1,
            multiMode: false,
            uploadTabIndex: 2,
            fileList: [] as FileType[],
            isGenerating: false,
            pollingTimer: null as number | null,
            taskId: ''
        }
    },
    computed: {
        // 图片图标引用
        imageIcon() {
            return AddPicture;
        },
        canGenerate(): boolean {
            const currentEffect = this.effects[this.selectedEffectIndex];
            if (currentEffect.limit === 2) {
                // 如果是双人特效，需要上传一张或两张图片
                return this.fileList.length > 0 && !this.isGenerating;
            }
            // 单人特效只需要一张图片
            return this.fileList.length === 1 && !this.isGenerating;
        }
    },
    methods: {
        selectMode(val: number) {
            this.selectedMode = val;
            this.showModeDropdown = false;
        },
        handleUploadChange(file: FileType[]) {
            this.fileList = file;
        },
        async handleGenerate() {
            if (!this.canGenerate) return;

            try {
                this.isGenerating = true;
                Message.loading({
                    content: '视频生成中...',
                    duration: 0,
                    closable: true
                });

                const currentEffect = this.effects[this.selectedEffectIndex];
                let params;
                
                if (currentEffect.limit === 2) {
                    // 双人特效，传入图片数组
                    params = {
                        imgs: this.fileList.map(file => file.url),
                        effect_type: currentEffect.effect_type
                    };
                } else {
                    // 单人特效，传入单张图片
                    params = {
                        img: this.fileList[0].url,
                        effect_type: currentEffect.effect_type
                    };
                }

                let response;
                if (currentEffect.limit === 1) {
                    // 单图特效视频
                    response = await getOneImageEffectsVideo(params);
                } else {
                    // 多图特效视频
                    response = await getMultiImageEffectsVideo(params);
                }
                
                this.taskId = response.data;
                await this.checkTaskStatus();
                this.startPolling();
            } catch (error) {
                console.error('Generate error:', error);
                Message.error('生成失败，请重试');
                this.isGenerating = false;
            }
        },

        async checkTaskStatus() {
            try {
                const response = await getEffectsVideoResult({ task_id: this.taskId });
                const result = response.data as VideoTaskResult;

                if (result.task_status === 2) { // 成功
                    this.stopPolling();
                    Message.clear();
                    Message.success('视频生成成功');
                    this.$emit('video-generated', result.task_result);
                    this.isGenerating = false;
                    return true;
                } else if (result.task_status === 3) { // 失败
                    this.stopPolling();
                    Message.clear();
                    Message.error(result.task_msg || '视频生成失败');
                    this.isGenerating = false;
                    return true;
                }
                return false; // 继续轮询
            } catch (error) {
                console.error('Check status error:', error);
                this.stopPolling();
                Message.clear();
                Message.error('查询任务状态失败');
                this.isGenerating = false;
                return true; // 发生错误，停止轮询
            }
        },

        async startPolling() {
            if (this.pollingTimer) {
                clearInterval(this.pollingTimer);
            }

            this.pollingTimer = window.setInterval(async () => {
                const shouldStop = await this.checkTaskStatus();
                if (shouldStop) {
                    this.stopPolling();
                }
            }, 5000); // 每5秒轮询一次
        },

        stopPolling() {
            if (this.pollingTimer) {
                clearInterval(this.pollingTimer);
                this.pollingTimer = null;
            }
        }
    },
    watch: {
        selectedEffectIndex(newIndex: number) {
            // 当切换到limit为1的特效时，自动切换到单张照片上传模式
            if (this.effects[newIndex].limit === 1) {
                this.uploadTabIndex = 1;
                // 清空已上传的图片
                this.fileList = [];
            }
        }
    },
    mounted() {
        document.body.setAttribute('arco-theme', 'dark');
        // 初始化时根据当前特效的limit设置uploadTabIndex
        if (this.effects[this.selectedEffectIndex].limit === 1) {
            this.uploadTabIndex = 1;
        }
    },
    beforeUnmount() {
        this.stopPolling();
    }
});
</script>

<style scoped>
:deep(.arco-scrollbar-track-direction-vertical) {
    right: -20px !important;
}
</style>